package com.rongshu.sendmessage.view.bottomView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.UpFileBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.GetBitmapByURL;
import com.rongshu.sendmessage.util.ObjectUtil;
import com.rongshu.sendmessage.util.PhotoImageLoader;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.Utils;
import com.rongshu.sendmessage.util.addimage.ImageResultCallback;
import com.rongshu.sendmessage.util.addimage.ProcessImageUtil;
import com.rongshu.sendmessage.util.addimage.UIUtils;
import com.rongshu.sendmessage.util.addimage.UpFileUtil;
import com.rongshu.sendmessage.util.httpUtil.Common;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.upData.UpdateManager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static android.view.View.GONE;
import static com.rongshu.sendmessage.util.DialogUtil.hideProgress;

public class HeadImageBottomDialog implements View.OnClickListener{
    private final String imageUrl;
    private final UpImageBackLisner callBack;
    private View inflate;
    private Context mContext;
    private BottomSheetDialog bsd1;
//    private ProcessImageUtil mImageUtil;


    public HeadImageBottomDialog(String imageUrl,UpImageBackLisner callBack){
        this.imageUrl=imageUrl;
        this.callBack=callBack;
    }
    public View showDialog(Context context) {
        //自定义dialog显示布局
        inflate = LayoutInflater.from(context).inflate(R.layout.head_bottom_view, null);
        mContext=context;
        initView(inflate);
        //自定义dialog显示风格
        bsd1=new BottomSheetDialog(mContext);
        inflate.post(new Runnable() {
            @Override
            public void run() {
                BottomSheetBehavior behavior= BottomSheetBehavior.from(bsd1.findViewById(R.id.design_bottom_sheet));
                behavior.setHideable(false);//此处设置表示禁止BottomSheetBehavior的执行
            }
        });

        bsd1.setContentView(inflate);
        bsd1.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        bsd1.setCanceledOnTouchOutside(false);
//        bsd1.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

        bsd1.show();
        bsd1.setCanceledOnTouchOutside(false);
        return inflate;
    }
    public boolean isShow(){
        return bsd1.isShowing();
    }
    private void initView(View inflate) {
        View tv_see_last = inflate.findViewById(R.id.tv_see_last);
        View tv_cancel = inflate.findViewById(R.id.tv_cancel);
        View tv_save = inflate.findViewById(R.id.tv_save);
        View tv_xiangce = inflate.findViewById(R.id.tv_xiangce);
        tv_see_last.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        tv_xiangce.setOnClickListener(this);
//        mImageUtil = new ProcessImageUtil((BaseActivity)mContext);
//        mImageUtil.setImageResultCallback( new ImageResultCallback() {
//            @Override
//            public void beforeCamera() {
//            }
//            @Override
//            public void onSuccess(File file1) {
//                Bitmap bitmap = BitmapFactory.decodeFile(file1.getAbsolutePath());
//                Uri uri = FileProvider.getUriForFile(mContext, mContext.getPackageName()+".fileImageProvider", file1);
//                upLoadImg(bitmap,uri+"",file1);
//            }
//
//            @Override
//            public void onSuccess(File file1, Uri uri) {
//                Bitmap bitmap = UIUtils.getBitmapFromUri(mContext,uri);
//                upLoadImg(bitmap,uri + "",file1);
//
//            }
//
//
//            @Override
//            public void onFailure() {
//                Log.e( "ddd", "onFailure" );
//            }
//        } );
        initPhotoPicker();
    }
    /**
     * 初始化图片选择器
     */
    private void initPhotoPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PhotoImageLoader());  //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSelectLimit(1);

        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(ObjectUtil.dip2px(mContext,300));   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(ObjectUtil.dip2px(mContext,300));  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setMultiMode(false);
    }

    //上传头像
    @SuppressLint("HandlerLeak")
    private void upLoadImg(Bitmap bitmap, String uri, File file) {
//上传图片
//        UpFileUtil.upFile(new HYContent().SET_USER_HEAD_URL,bitmap,file,new Handler(){
//            @Override
//            public void handleMessage(@SuppressLint("HandlerLeak") @NonNull Message msg) {
//                super.handleMessage(msg);
//                if(msg.what==UpFileUtil.SAVE_SUCCESS){
//                    String body=msg.obj+"";
//                    Log.e("upFile","上传成功" + body);
////                    UpFileBean bean= JSON.parseObject(body, UpFileBean.class);
//                    bsd1.dismiss();
//                    callBack.upImageBack(200,bitmap);
//                }else if (msg.what==UpFileUtil.SAVE_FIAL){
//                    bsd1.dismiss();
//                    callBack.upImageBack(-1,null);
//                }
//            }
//        });
    }


    public interface UpImageBackLisner{
        void upImageBack();
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.tv_see_last){
            ToastUtils.show(mContext,"查看上一次的图片开发中");
        }else if (v.getId()==R.id.tv_cancel){
            bsd1.dismiss();

        }else if (v.getId()==R.id.tv_save){
            GetBitmapByURL.getBitmap(imageUrl,handler);


        }else if (v.getId()==R.id.tv_xiangce){
            callBack.upImageBack();
            bsd1.dismiss();
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@SuppressLint("HandlerLeak") @NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1234){
                if (msg.obj!=null){
                    Bitmap bitmap=GetBitmapByURL.setBitMap((Bitmap) msg.obj);
                    String _path= Utils.getTakePhotoPath()+ File.separator+"sendMessageHead.jpg";
                    saveSign(bitmap, _path);
                    bsd1.dismiss();
                }
            }
        }
    };
    private void saveSign(Bitmap bitmap, String path) {
        try{
            createFile(bitmap,path);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void createFile(Bitmap bitmap,String path) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.WEBP, 100, baos);
            byte[] photoBytes = baos.toByteArray();
            if (photoBytes != null) {
                new FileOutputStream(new File(path)).write(photoBytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null)
                    baos.close();
                Toast.makeText(mContext, "保存成功！", Toast.LENGTH_SHORT).show();
                //通知相册更新
                MediaStore.Images.Media.insertImage(mContext.getContentResolver(), BitmapFactory.decodeFile(new File(path).getAbsolutePath()), new File(path).getName(), null);
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(new File(path));
                intent.setData(uri);
                mContext.sendBroadcast(intent);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
